//
//  DataCach.m
//  Remind
//
//  Created by mac on 2017/10/8.
//  Copyright © 2017年 2017.09.27. All rights reserved.
//

#import "DataCach.h"
#import "LGSideMenuController.h"
#import "LoginViewController.h"
#import "LeftMenuViewController.h"
#import "UIViewController+LGSideMenuController.h"
#import "AppDelegate.h"

@interface DataCach ()
@property (strong, nonatomic) NSUserDefaults *userDefaults;
@property (strong, nonatomic) NSString *userName;
@end

static DataCach *dataCach;
@implementation DataCach

#pragma mark - 单例
+ (instancetype)sharedUserDefault{
    static dispatch_once_t onc;
    dispatch_once(&onc, ^{
        dataCach = [[DataCach alloc] init];
        dataCach.userDefaults = [NSUserDefaults standardUserDefaults];
    });
    return dataCach;
}

- (NSString *)userName{
    if(!_userName){
        _userName = @"NO";
    }
    return _userName;
}

#pragma mark - 删除数据
+ (BOOL)removeValueByClassName:(NSString * __nonnull)classname{
    if(!dataCach){
        dataCach = [self sharedUserDefault];
    }
    NSMutableDictionary *user_Dict = [dataCach.userDefaults objectForKey:dataCach.userName];
    id object = [user_Dict objectForKey:classname];
    if(!object) return YES;
    [user_Dict removeObjectForKey:classname];
    [dataCach.userDefaults setObject:user_Dict forKey:dataCach.userName];
    if([user_Dict objectForKey:classname]){
        return NO;
    }
    return YES;
}

#pragma mark - 设置当前的用户名和状态
+ (void)setUserInformation:(NSString *)name{
    NSDictionary *dict = @{
                           @"ifLogin" : @1,
                           @"name" : name
                           };
    [[NSUserDefaults standardUserDefaults] setObject:dict forKey:@"userInformation"];
}

#pragma mark - 获取当前的用户名和状态
+ (NSDictionary *)getUserInformation{
    if(!dataCach){
        dataCach = [self sharedUserDefault];
    }
    NSDictionary *dict = [dataCach.userDefaults objectForKey:@"userInformation"];
    if(!dict){
        dict = @{
                 @"ifLogin" : @0,
                 @"name" : @"NOT"
                 };
    }
    NSLog(@"当前用户:%@",dict);
    dataCach.userName = [dict objectForKey:@"name"];
    return dict;
}

#pragma mark - 获取数据
+ (id)getValueByClassName:(NSString * __nonnull)classname{
    if(!dataCach){
       dataCach = [self sharedUserDefault];
    }
    NSDictionary *dict = [self getUserInformation];
    NSNumber *number = [dict objectForKey:@"ifLogin"];
    if(![number intValue]){
        NSLog(@"！！！未登录！！！");
        UIViewController *con = [self getCurrentViewController];
        UIStoryboard *story = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];
        LoginViewController *loginCon = [story instantiateViewControllerWithIdentifier:@"loginCon"];
        [con.navigationController pushViewController:loginCon animated:YES];
        return nil;
        
    }
    
    NSMutableDictionary *user_Dict = [dataCach.userDefaults objectForKey:dataCach.userName];
    if(!user_Dict) {
        user_Dict = [NSMutableDictionary new];
        [dataCach.userDefaults setObject:user_Dict forKey:dataCach.userName];
        NSLog(@"初始化用户");
    } else NSLog(@">>__--__-->>用户数据:%@",user_Dict);
    id obj = [user_Dict objectForKey:classname];
    NSLog(@">>%@__请求数据:%@",classname,obj);
    return obj?[obj copy]:nil;
}

#pragma mark - 设置数据
+ (void)setUserData:(id __nonnull)data forClassName:(NSString * __nonnull)classname{
    NSMutableDictionary *user_Dict = [[NSMutableDictionary alloc] initWithDictionary:[dataCach.userDefaults objectForKey:dataCach.userName]];
    [user_Dict setObject:data forKey:classname];
    [dataCach.userDefaults setObject:user_Dict forKey:dataCach.userName];
}

+ (BOOL)setObject:(id __nonnull)obj forClassName:(NSString * __nonnull)classname IfTheDataIsNullInitialized:(Class __nonnull)class ReplaceData:(BOOL)replace{
    if(!dataCach){
        dataCach = [self sharedUserDefault];
    }
    NSMutableDictionary *user_Dict = [dataCach.userDefaults objectForKey:dataCach.userName];
    
    id object = [user_Dict objectForKey:classname];
    
    if(!object) {
        object = [[class alloc] init];
        //[self setUserData:object forClassName:classname];
    }
    if(replace) {
        [self setUserData:obj forClassName:classname];
        return YES;
    }
    if([object isKindOfClass:[NSArray class]]||[object isKindOfClass:[NSMutableArray class]]){
        NSLog(@"是数组对象");
        NSMutableArray *arr = [NSMutableArray arrayWithArray:object];
        [arr addObject:obj];
        
        [self setUserData:arr forClassName:classname];
        return YES;
    }
    if([object isKindOfClass:[NSMutableDictionary class]]||[object isKindOfClass:[NSDictionary class]]){
        NSLog(@"是字典对象");
        NSMutableDictionary *event_Dict = [[NSMutableDictionary alloc] initWithDictionary:object];
        NSMutableDictionary *obj_Dict = obj;

        [event_Dict setObject:[obj_Dict objectForKey:obj_Dict.allKeys.firstObject] forKey:obj_Dict.allKeys.firstObject];

        [self setUserData:event_Dict forClassName:classname];
        return YES;
    }
//    if([obj isKindOfClass:[NSString class]]){
//        NSLog(@"NSNUMBER");
//        [self setUserData:obj forClassName:classname];
//    }
    return NO;
}

#pragma mark - 获取分类标签
+ (NSArray *)GetTheSortedArray{
    if(!dataCach){
        dataCach = [self sharedUserDefault];
    }
    //[self getUserInformation];
    
    NSArray *sortArr = [self getValueByClassName:@"sort"];
    
    if(!sortArr){
        sortArr = [NSArray arrayWithObjects:@"默认",@"工作",@"生活",@"纪念日",nil];
        NSMutableDictionary *user_Dict = [[NSMutableDictionary alloc] initWithDictionary:[dataCach.userDefaults objectForKey:dataCach.userName]];
        [user_Dict setObject:sortArr forKey:@"sort"];
        [dataCach.userDefaults setObject:user_Dict forKey:dataCach.userName];
    }
    //NSLog(@"%@",sortArr);
    return [sortArr copy];
}

 #pragma mark - 其它功能_-_-_-_-_-_-_-_-_-_-_-_--_-_-_-_-_-___-_
+ (void)selectSideMenuPushViewController:(UIViewController *)viewCon Index:(NSInteger)idx{
    UIViewController *currentCon = [self getCurrentViewController];
    LGSideMenuController *sideMenuCon = [currentCon sideMenuController];
    AppDelegate *appDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    appDelegate.leftSideMenuIdx = idx;
    [appDelegate.shadownView removeFromSuperview];
    
    [viewCon.view addSubview:appDelegate.shadownView];
    UINavigationController *navCon = [[UINavigationController alloc] initWithRootViewController:viewCon];
    navCon.navigationBar.barTintColor = [UIColor whiteColor];
    sideMenuCon.rootViewController = navCon;
    [sideMenuCon hideLeftViewAnimated:YES completionHandler:nil];
    
}

+ (NSString *)networkingStatesFromStatebar {
    // 状态栏是由当前app控制的，首先获取当前app
    UIApplication *app = [UIApplication sharedApplication];
    
    NSArray *children = [[[app valueForKeyPath:@"statusBar"] valueForKeyPath:@"foregroundView"] subviews];
    
    int type = 0;
    for (id child in children) {
        if ([child isKindOfClass:[NSClassFromString(@"UIStatusBarDataNetworkItemView") class]]) {
            type = [[child valueForKeyPath:@"dataNetworkType"] intValue];
        }
    }
    
    NSString *stateString = @"";
    
    switch (type) {
        case 0:
            stateString = @"notReachable";
            break;
            
        case 1:
            stateString = @"2G";
            break;
            
        case 2:
            stateString = @"3G";
            break;
            
        case 3:
            stateString = @"4G";
            break;
            
        case 4:
            stateString = @"LTE";
            break;
            
        case 5:
            stateString = @"wifi";
            break;
            
        default:
            break;
    }
    
    return stateString;
}

+ (UIViewController *)getCurrentViewController
{
    
    UIViewController *con = [UIApplication sharedApplication].keyWindow.rootViewController;
    
    while (YES) {
        if([con isKindOfClass:LGSideMenuController.class]){
            LGSideMenuController *sideMenuCon = (LGSideMenuController *)con;
            con = sideMenuCon.rootViewController;
        }else if ([con isKindOfClass:UINavigationController.class]) {
            UINavigationController *nav = (UINavigationController *)con;
            con = nav.viewControllers.lastObject;
        }else if ([con isKindOfClass:UITabBarController.class]) {
            UITabBarController *tab = (UITabBarController *)con;
            con = tab.viewControllers[tab.selectedIndex];
        }else if (con.presentedViewController) {
            con = con.presentedViewController;
        }else{
            break;
        }
    }
    return con;
}


//给textField加上收件盘的按钮
+ (void)addTextFieldInputAccessoryView:(id _Nonnull )textField{

    CGRect rect = [UIScreen mainScreen].bounds;
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, rect.size.width, 44)];
    lineView.backgroundColor = [UIColor whiteColor];
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.frame = CGRectMake(rect.size.width - 58, 0, 50, 44);
    [btn setTitle:@"Done" forState:UIControlStateNormal];
    [btn setTitleColor:[UIColor colorWithRed:44/255.0 green:124/255.0 blue:246/255.0 alpha:1.0] forState:UIControlStateNormal];
    btn.font = [UIFont fontWithName:@"Helvetica-Bold" size:18];
    [btn addTarget:self action:@selector(done) forControlEvents:UIControlEventTouchUpInside];
    [lineView addSubview:btn];
    if([textField isKindOfClass:[UITextField class]]){
        UITextField *txtField = (UITextField *)textField;
        txtField.inputAccessoryView = lineView;
    } else if([textField isKindOfClass:[UITextView class]]) {
        UITextView *txtView = (UITextView *)textField;
        txtView.inputAccessoryView = lineView;
    }
}

+ (void)done{
    [[[UIApplication sharedApplication] keyWindow] endEditing:YES];
}

@end
